using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.ResponseCompression;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Net.Http;
using System.Net.Http.Headers;
using System.IO.Compression;

var builder = WebApplication.CreateBuilder(args);

// 添加响应压缩服务
builder.Services.AddResponseCompression(options =>
{
    options.Providers.Add<GzipCompressionProvider>();
    options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
        new[] { "application/javascript", "text/css", "text/html" });
});

// 配置Gzip压缩级别
builder.Services.Configure<GzipCompressionProviderOptions>(options =>
{
    options.Level = CompressionLevel.Optimal;
});

// 添加HTTP客户端服务
builder.Services.AddHttpClient("BaiduClient", client =>
{
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html"));
    client.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36");
}).ConfigurePrimaryHttpMessageHandler(() =>
{
    return new HttpClientHandler
    {
        UseDefaultCredentials = true,
        AutomaticDecompression = System.Net.DecompressionMethods.GZip | System.Net.DecompressionMethods.Deflate
    };
});

// 添加AngleSharp服务
builder.Services.AddSingleton<AngleSharp.IBrowsingContext>(provider =>
{
    return AngleSharp.BrowsingContext.New(AngleSharp.Configuration.Default);
});

// 添加控制器服务
builder.Services.AddControllers();

var app = builder.Build();

// 配置中间件
if (app.Environment.IsDevelopment())
{
    // 开发环境配置
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();

// 启用响应压缩
app.UseResponseCompression();

// 配置路由
app.MapControllers();
app.MapFallbackToFile("index.html");

// 在控制台显示启动信息
Console.WriteLine("URL采集工具正在启动...");
Console.WriteLine("服务将运行在: http://localhost:5000");
Console.WriteLine("按Ctrl+C停止服务");

// 明确指定端口
app.Run("http://localhost:5000");